package top.lidee.module.schedule.twice.management;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import top.lidee.common.bean.WxPayV3Bean;
import top.lidee.common.service.twice.management.MtStoreWechatInputPieceLogService;
import top.lidee.common.service.twice.management.MtStoreWechatInputRejectTableService;
import top.lidee.common.service.twice.third.wechat.WechatPayJJCommonService;
import top.lidee.common.to.wx.ty.Audit_detail;
import top.lidee.common.to.wx.ty.WxSelectIncomingPartsTyTo;
import top.lidee.repository.model.twice.pojo.management.MtStoreWechatInputPieceLogEntity;
import top.lidee.repository.model.twice.pojo.management.MtStoreWechatInputRejectTableEntity;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import static top.lidee.framework.constant.WechatConstant.*;

/**
 * @author 张一恒
 * @version 1.0
 * @description: 微信收款 特约进件 查询申请状态API
 * @date 2024/10/8 16:27
 */
@Component
@Slf4j
public class WechatPayTyJJSelectJob {

    @Autowired
    private WxPayV3Bean wxPayV3Bean;

    @Autowired
    private MtStoreWechatInputPieceLogService mtStoreWechatInputPieceLogService;

    @Autowired
    private WechatPayJJCommonService wechatPayJJCommonService;

    @Autowired
    private MtStoreWechatInputRejectTableService mtStoreWechatInputRejectTableService;


    /**
     * @return void
     * @description 申请单状态
     * <p>
     * 1、APPLYMENT_STATE_EDITTING（编辑中）：提交申请发生错误导致，请尝试重新提交。
     * 2、APPLYMENT_STATE_AUDITING（审核中）：申请单正在审核中，超级管理员用微信打开“签约链接”，完成绑定微信号后，申请单进度将通过微信公众号通知超级管理员，引导完成后续步骤。
     * 3、APPLYMENT_STATE_REJECTED（已驳回）：请按照驳回原因修改申请资料，超级管理员用微信打开“签约链接”，完成绑定微信号，后续申请单进度将通过微信公众号通知超级管理员。
     * 4、APPLYMENT_STATE_TO_BE_CONFIRMED（待账户验证）：请超级管理员使用微信打开返回的“签约链接”，根据页面指引完成账户验证。
     * 5、APPLYMENT_STATE_TO_BE_SIGNED（待签约）：请超级管理员使用微信打开返回的“签约链接”，根据页面指引完成签约。
     * 6、APPLYMENT_STATE_SIGNING（开通权限中）：系统开通相关权限中，请耐心等待。
     * 7、APPLYMENT_STATE_FINISHED（已完成）：商户入驻申请已完成。
     * 8、APPLYMENT_STATE_CANCELED（已作废）：申请单已被撤销。
     * @author zhangyiheng
     * @date 2024/10/22 09:52
     */
    //    @Scheduled
    @Transactional
    public void tyJJCheckApplicationStatus() {
        log.info("=============微信特约进件查询申请状态API Start=============");
        //查询收付通日志表
        List<MtStoreWechatInputPieceLogEntity> listed = mtStoreWechatInputPieceLogService.list(Wrappers.<MtStoreWechatInputPieceLogEntity>lambdaQuery()
                .eq(MtStoreWechatInputPieceLogEntity::getState, IN_THE_INCOMING));

        AtomicInteger successCount = new AtomicInteger(0);
        AtomicInteger failedCount = new AtomicInteger(0);
        AtomicInteger resFailedCount = new AtomicInteger(0);
        Optional.ofNullable(listed).ifPresent(item -> {

            for (MtStoreWechatInputPieceLogEntity pieceLog : item) {
                //优先使用申请单号查询
                String url = "";
                if (Objects.nonNull(pieceLog.getApplymentId())) {
                    url = wxPayV3Bean.getApplymentId4Url() + pieceLog.getApplymentId();
                } else {
                    url = wxPayV3Bean.getBusinessCodeUrl() + pieceLog.getOutRequestNo();
                }

                Map<String, Object> map = wechatPayJJCommonService.pushRequestOfGetApply(url, "特约进件");
                String res = (String) map.get("res");
                int code = (int) map.get("code");

                if (Objects.equals(code, 200)) {
                    WxSelectIncomingPartsTyTo to = JSON.parseObject(res, WxSelectIncomingPartsTyTo.class);

                    MtStoreWechatInputPieceLogEntity logEntity = getMtStoreWechatInputPieceLogEntity(pieceLog, to, code, successCount);


                    //保存收付通进件日志
                    mtStoreWechatInputPieceLogService.saveOrUpdate(logEntity);

                    //保存收付通驳回原因详情
                    saveTheReasonForTheRejection(pieceLog, to, failedCount);
                    log.info("=============微信特约进件查询申请状态API 处理成功，店铺id：{}=============", pieceLog.getStoreId());
                } else {
                    resFailedCount.incrementAndGet();
                }

            }
        });

        log.debug("=====微信特约进件查询申请状态API 审核成功:{},审核失败:{},请求失败:{}=====,", successCount.get(), failedCount.get(), resFailedCount.get());
        log.info("=============微信特约进件查询申请状态API End=============");
    }


    /**
     * @param pieceLog
     * @param to
     * @param failedCount
     * @return void
     * @description 保存特约进件驳回原因详情
     * @author zhangyiheng
     * @date 2024/10/22 10:15
     */
    private void saveTheReasonForTheRejection(MtStoreWechatInputPieceLogEntity pieceLog, WxSelectIncomingPartsTyTo to, AtomicInteger failedCount) {
        Optional.ofNullable(to.getAudit_detail()).ifPresent(auditDetails -> {
            List<MtStoreWechatInputRejectTableEntity> detailEntities = new ArrayList<>();
            for (Audit_detail auditDetail : auditDetails) {
                MtStoreWechatInputRejectTableEntity detail = new MtStoreWechatInputRejectTableEntity();

                detail.setField(auditDetail.getField());
                detail.setFieldName(auditDetail.getField_name());
                detail.setRejectReason(auditDetail.getReject_reason());
                detail.setWechatInputPieceId(pieceLog.getId());
                detailEntities.add(detail);
            }
            mtStoreWechatInputRejectTableService.saveBatch(detailEntities);
            failedCount.incrementAndGet();
        });
    }

    /**
     * @param pieceLog
     * @param to
     * @param code
     * @param successCount
     * @return top.lidee.repository.model.twice.pojo.management.MtStoreWechatInputPieceLogEntity
     * @description 组装查询申请状态API 基本参数
     * @author zhangyiheng
     * @date 2024/10/22 10:15
     */
    private MtStoreWechatInputPieceLogEntity getMtStoreWechatInputPieceLogEntity(MtStoreWechatInputPieceLogEntity pieceLog, WxSelectIncomingPartsTyTo to, int code, AtomicInteger successCount) {
        MtStoreWechatInputPieceLogEntity log = new MtStoreWechatInputPieceLogEntity();
        log.setApplymentId(to.getApplyment_id());
        log.setOutRequestNo(to.getBusiness_code());
        log.setStatusCode(code);
        log.setStoreId(pieceLog.getStoreId());
        String applymentState = to.getApplyment_state();
        switch (applymentState) {
            case APPLYMENT_STATE_AUDITING: //审核中
            case APPLYMENT_STATE_TO_BE_CONFIRMED: //待账户验证
            case APPLYMENT_STATE_TO_BE_SIGNED: //待签约
            case APPLYMENT_STATE_SIGNING: //开通权限中
                log.setState(IN_THE_INCOMING);
                break;
            case APPLYMENT_STATE_FINISHED: //已完成
                log.setState(THE_INCOMING_REVIEW_IS_COMPLETE);
                successCount.incrementAndGet();
                break;
            case APPLYMENT_STATE_EDITTING: //编辑中
            case APPLYMENT_STATE_REJECTED: //已驳回
            case APPLYMENT_STATE_CANCELED: //已作废
                log.setState(INCOMING_ITEMS_ARE_ABNORMAL);
                break;
            default:
                break;
        }
        log.setApplymentState(applymentState);
        log.setApplymentStateDesc(to.getApplyment_state_msg());
        log.setSignUrl(to.getSign_url());
        log.setSubMchid(to.getSub_mchid());
        return log;
    }


}
